﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using ComicIsland.Common;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views
{
    /// <summary>
    /// 漫画阅读页
    /// <para>如果阅读过就直接阅读随后一章节，如果是新书则进入章节目录</para>
    /// <para>获取章节信息：comic/downloadcomicsview_v3?bookid=22476</para>
    /// <para>获取漫画图片信息：comic/comicsread_v3?bookid=22476&partid=105&parturl=</para>
    /// </summary>
    public partial class ComicReaderPage : PhoneApplicationPage
    {
        private string comicId = string.Empty, partId = string.Empty, partUrl = string.Empty;
        private int pageSize = 10, pageIndex = 0;
        private JsonComicContentInfo currentSelectedItem;
        private ObservableCollection<JsonComicContentInfo> itemsource = new ObservableCollection<JsonComicContentInfo>();
        public ComicReaderPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            //NaviService.Navigate(ComicIslandPage.ComicReaderPage, string.Concat("?comicId=", item.Sourceparturl, "&partid=", item.PartId, "&parturl=", Uri.EscapeDataString(item.Sourceparturl)));
            if (!base.NavigationContext.QueryString.ContainsKey("comicId"))
            {
                base.NavigationService.GoBack();
                return;
            }
            comicId = base.NavigationContext.QueryString["comicId"];
            if (string.IsNullOrWhiteSpace(comicId))
            {
                base.NavigationService.GoBack();
                return;
            }

            if (!base.NavigationContext.QueryString.ContainsKey("partid"))
            {
                base.NavigationService.GoBack();
                return;
            }
            partId = base.NavigationContext.QueryString["partid"];
            //if (string.IsNullOrWhiteSpace(partId))
            //{
            //    base.NavigationService.GoBack();
            //    return;
            //}
            if (!base.NavigationContext.QueryString.ContainsKey("parturl"))
            {
                base.NavigationService.GoBack();
                return;
            }
            partUrl = base.NavigationContext.QueryString["parturl"];
            //if (string.IsNullOrWhiteSpace(partUrl))
            //{
            //    base.NavigationService.GoBack();
            //    return;
            //}

            this.LoadComicContent(comicId, partId, partUrl);
        }


        private void LoadComicContent(string comicId, string partId, string partUrl)
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, string.Format("/comic/comicsread_v3?bookid={0}&partid={1}&parturl={2}&partVersion=3", comicId.ToString(), partId, string.IsNullOrWhiteSpace(partUrl) ? "" : Uri.EscapeDataString(partUrl)));
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"info\":{}") >= 0)
                        {
                            LogHelper.LogError("未找到对应漫画！", this.GetType(), MethodBase.GetCurrentMethod());
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicContent>(result);
                        if (!(rootCharacterString != null && !string.IsNullOrWhiteSpace(rootCharacterString.Info)))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            itemsource = JSONHelper.Deserialize<ObservableCollection<JsonComicContentInfo>>(rootCharacterString.Info);
                            if (itemsource != null && itemsource.Count > 0)
                            {
                                if (itemsource.Count <= 1)
                                {
                                    JsonComicContentInfo contentInfo = (from p in itemsource select p).FirstOrDefault<JsonComicContentInfo>();
                                    if (contentInfo != null && !string.IsNullOrWhiteSpace(contentInfo.Referer))
                                    {
                                        //this.webBrowser.Navigate(new Uri(contentInfo.Imgurl, UriKind.Absolute));
                                        this.webBrowser.Navigate(new Uri(contentInfo.Referer, UriKind.Absolute));
                                        this.webBrowser.Navigating += webBrowser_Navigating;
                                        this.webBrowser.Navigated += webBrowser_Navigated;
                                        this.webBrowser.NavigationFailed += webBrowser_NavigationFailed;
                                    }
                                }
                                else
                                {
                                    var currentItems = itemsource.Skip(pageSize * pageIndex).Take(pageSize).ToList<JsonComicContentInfo>();
                                    if (currentItems != null && currentItems.Count > 0)
                                    {
                                        pageIndex++;
                                        BindComicImage(new ObservableCollection<JsonComicContentInfo>(currentItems));
                                    }
                                }
                            }
                        }

                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {

                }
            }, webTask);
        }


        void BindComicImage(ObservableCollection<JsonComicContentInfo> items, int pageIndex = 0)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                this.panorama.Items.Clear();
                this.panelSelectedIndex.Children.Clear();

                bool IsFirstSelected = true;
                for (int i = 0; i < items.Count; i++)
                {
                    JsonComicContentInfo item = items[i];
                    if (item == null)
                        continue;
                    if (string.IsNullOrWhiteSpace(item.Imgurl))
                        continue;
                    LogHelper.LogInfo(string.Concat("pageIndex=", pageIndex, ",URL=", item.Imgurl),this.GetType (),MethodBase.GetCurrentMethod());
                    PanoramaItem pi = new PanoramaItem();
                    pi.Margin = new Thickness(-14, -36, 5, 0); //new Thickness(-12, -36, 0, 0);
                    pi.BorderThickness = new Thickness(0, 0, 5, 0);
                    //pi.ContentTemplate = this.panoramaItemDataTemplate;
                    BitmapImage bmp = new BitmapImage(new Uri(item.Imgurl, UriKind.RelativeOrAbsolute));
                    Image imageFocus = new Image();
                    imageFocus.Height = this.Height;
                    imageFocus.Width = this.Width;
                    imageFocus.Tag = item;
                    imageFocus.Source = bmp;
                    imageFocus.Stretch = System.Windows.Media.Stretch.Uniform;
                    pi.Content = imageFocus;
                    this.panorama.Items.Add(pi);
                    //
                    Border border = new Border();
                    border.BorderThickness = new Thickness(1);
                    border.BorderBrush = new SolidColorBrush(Helper.HexToColor("#ffff8c00"));
                    border.Height = 12;
                    border.Width = 30;
                    border.Margin = new Thickness(8, 0, 0, 0);
                    border.DataContext = item;
                    border.Tap += border_Tap;
                    border.Tag = i;
                    TextBlock txt = new TextBlock() { Text = (i + 1).ToString(), FontSize = 12, Margin = new Thickness(-10), FontFamily = new FontFamily("Microsoft Yahei"), VerticalAlignment = System.Windows.VerticalAlignment.Center, HorizontalAlignment = System.Windows.HorizontalAlignment.Center, Foreground = new SolidColorBrush(Helper.HexToColor("#ffff8c00")) };
                    border.Child = txt;
                    if (IsFirstSelected)
                    {
                        border.Tag = i;
                        border.Background = new SolidColorBrush(Helper.HexToColor("#ffbebebe"));
                        IsFirstSelected = false;
                    }
                    this.panelSelectedIndex.Children.Add(border);

                }
            });
        }


        void webBrowser_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            LogHelper.LogError(e.Exception.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void webBrowser_Navigated(object sender, NavigationEventArgs e)
        {
            LogHelper.LogError(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void webBrowser_Navigating(object sender, NavigatingEventArgs e)
        {
            LogHelper.LogError(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }


        void border_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }

        private void panorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            foreach (Border border in this.panelSelectedIndex.Children)
            {
                if (border == null)
                    return;
                JsonComicContentInfo dmi = border.DataContext as JsonComicContentInfo;
                if (dmi == null)
                    return;
                int index = 0;
                if (border.Tag != null)
                    int.TryParse(border.Tag.ToString(), out index);

                if (this.panorama.SelectedIndex == index)
                {
                    border.Background = new SolidColorBrush(Helper.HexToColor("#ffbebebe"));
                    currentSelectedItem = dmi;
                    //最后一张则取分页数据
                    if (index == this.panorama.Items.Count - 1)
                    {
                        var currentItems = itemsource.Skip(pageSize * pageIndex).Take(pageSize).ToList<JsonComicContentInfo>();
                        if (currentItems != null && currentItems.Count > 0)
                        {                            
                            BindComicImage(new ObservableCollection<JsonComicContentInfo>(currentItems),pageIndex);
                            pageIndex++;
                        }
                    }
                }
                else
                {
                    border.Background = new SolidColorBrush(Colors.Transparent);
                }
            }
        }

        private void panorama_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }



    }
}